package com.kye.express.business.personal;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.about.AboutActivity;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.comment.CommentListActivity;
import com.kye.express.business.customer_code.bind_customer_code.BindCustomerCodeActivity;
import com.kye.express.business.customer_code.customer_code_manager.CustomerCodeManagerActivity;
import com.kye.express.business.help.list.HelpActivity;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.business.personal_my_bill.monthly_balance_bill.list.MyBillListActivity;
import com.kye.express.business.personal_setting.PersonalSettingActivity;
import com.kye.express.business.share.ShareActivity;
import com.kye.express.business.welfare_integral.IntegralCenterActivity;
import com.kye.express.databinding.FragmentMainPersonalBinding;
import com.kye.express.utils.AppUtil;
import com.kye.express.view.ToastManager;
import com.kye.model.UserSession;
import com.kye.model.bean.user.User;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.functions.Consumer;

/**
 * @author : Joe
 * @version : 1.0
 * @editor : Joe
 * @created : 18/12/2017
 * @updated : 18/12/2017
 * @description : <Description>
 * @update_reason : <UpdateReason>
 */

public class PersonalFragment extends BaseAppCompatFragment implements PersonalContract.PersonalView {

    private PersonalContract.PersonalPresenter mPresenter;
    private FragmentMainPersonalBinding mBinding;
    private RxPermissions mRxPermissions;

    public static PersonalFragment newInstance() {
        Bundle args = new Bundle();
        PersonalFragment fragment = new PersonalFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main_personal, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        PersonalSvgModel personalSvgModel = new PersonalSvgModel(
                getActivity().getResources().getDrawable(R.drawable.icon_personal_my_bills),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_comment),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_commissioner),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_customer_code),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_share),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_help),
                getActivity().getResources().getDrawable(R.drawable.icon_personal_about));
        mBinding = FragmentMainPersonalBinding.bind(view);
        mBinding.setPersionSVG(personalSvgModel);
        adaptationHeight();
        initEvent();
    }

    private void initEvent() {
        RxView.clicks(mBinding.linearLayoutInfo)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivity(new Intent(getContext(), LoginActivity.class));
                    }
                });

        RxView.clicks(mBinding.superTextViewMyComment)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        CommentListActivity.startActivity(getActivity());
                    }
                });

        RxView.clicks(mBinding.imageButtonSettting)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivity(new Intent(getContext(), PersonalSettingActivity.class));
                    }
                });

        RxView.clicks(mBinding.superTextViewMyBills)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mBinding.getUser().isBalance()) {
                            MyBillListActivity.startActivity(getContext());
                        } else {
                            ToastManager.show(getContext(), "您暂无权限查看账单，请联系跨越专员授权");
                        }
                    }
                });

        RxView.clicks(mBinding.superTextViewCommissioner)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {

                    private MaterialDialog mDialog;

                    @Override
                    public void accept(Object o) throws Exception {
                        if (mDialog == null) {
                            mDialog = new MaterialDialog.Builder(getContext())
                                    .title(R.string.personal_commissioner_alert_title)
                                    .content(R.string.personal_commissioner_alert_message)
                                    .positiveText(R.string.personal_commissioner_alert_confirm)
                                    .negativeText(R.string.common_cancel)
                                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                                        @Override
                                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                            mRxPermissions.requestEach(Manifest.permission.CALL_PHONE)
                                                    .subscribe(new Consumer<Permission>() {
                                                        @Override
                                                        public void accept(Permission permission) throws Exception {
                                                            if (permission.granted) {
                                                                Intent intent = new Intent();
                                                                intent.setAction(Intent.ACTION_CALL);
                                                                intent.setData(Uri.parse("tel:" + mBinding.getUser().getKyeServicePhone()));
                                                                startActivity(intent);
                                                            } else {
                                                                ToastManager.show(getContext(), R.string.personal_commissioner_reject_permissions);
                                                            }
                                                        }
                                                    });
                                        }
                                    })
                                    .build();
                        }
                        mDialog.show();
                    }
                });

        RxView.clicks(mBinding.superTextViewCustomerCode)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (mBinding.getUser() == null || !mBinding.getUser().isLogin()) {
                            LoginActivity.startActivity(getContext());
                            return;
                        }
                        if (TextUtils.isEmpty(mBinding.getUser().getCustomCode())) {
                            BindCustomerCodeActivity.startActivity(getContext());
                        } else {
                            CustomerCodeManagerActivity.startActivity(getContext());
                        }
                    }
                });

        RxView.clicks(mBinding.superTextViewShare)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        startActivity(new Intent(getContext(), ShareActivity.class));
                    }
                });

        RxView.clicks(mBinding.superTextViewHelp)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        HelpActivity.startActivity(getContext());
                    }
                });

        RxView.clicks(mBinding.superTextViewAbout)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        AboutActivity.startActivity(getContext());
                    }
                });

        RxView.clicks(mBinding.integral)
                .compose(new DebounceObservableTransformer<Object>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        IntegralCenterActivity.startActivity(getContext());
                    }
                });
    }

    @Override
    protected void initData(@Nullable Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mPresenter = new PersonalContract.PersonalPresenter();
        mPresenter.bind(this);
        if (getActivity() != null) {
            mRxPermissions = new RxPermissions(getActivity());
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mPresenter.hasNewBill();
    }

    @Override
    public void onUser(User user) {
        mBinding.setUser(user);
    }

    @Override
    public void onCommentCount(int commentCount) {
        mBinding.setCommentCount(12);
    }

    @Override
    public void onBalance(float balance) {
        mBinding.setBalance(2527F);
    }

    @Override
    public void onCredits(int credits) {
        mBinding.setCredits(54529);
    }

    @Override
    public void onNewBillsVisibility(boolean newBillsVisibility) {
        mBinding.setNewBillsVisibility(newBillsVisibility);
    }

    public void adaptationHeight(){
        if(AppUtil.getSDKVersion() == 19 || AppUtil.getSDKVersion() == 20){
            FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(0, AppUtil.getStatusBarHeight(), 0, 0);
            mBinding.NestedScrollViewPersonal.setLayoutParams(lp);
        }
    }
}
